package com.nowcoder.community.service;
import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.util.SensitiveFilter;
import com.nowcoder.community.util.XaCommunityConstant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import javax.annotation.Resource;
import java.util.List;
import static com.nowcoder.community.util.XaCommunityConstant.ENTITY_TYPE_POST;
@Service
public class CommentService implements XaCommunityConstant {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private SensitiveFilter sensitiveFilter;
    @Resource
    private DiscussPostService discussPostService;
    public List<Comment>findCommentsByEntity(int entityType, int entityId, 
                                             int offset, int limit){
        return commentMapper.selectCommentsByEntity(entityType,entityId,offset,limit);
    }
    //通过实体查询评论
    public int findCommentCount(int entityType, int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if(comment==null)throw new IllegalArgumentException("参数不能为空!!");
        
        //添加评论--设置评论内容--并且转义html，过滤敏感词
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        
        
        //更新帖子评论数量
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            //查询对应评论种类和id所对应评论的数量
            int count=commentMapper.selectCountByEntity(
                    comment.getEntityType(),comment.getEntityId());
            //更新帖子的评论数量属性
            discussPostService.updateCommentCount(comment.getEntityId(),count);
        }
        return rows;
    } //给帖子新增评论

    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }
}
